#include "mono/Clazz.h"

using namespace mono;

bool Clazz::Init()
{
    // ztclog::info("try get clazz %s %s", m_Desc.m_Namespace.c_str(), m_Desc.m_Name.c_str());
    klass = mono_class_from_name(m_Desc.image, m_Desc.m_Namespace.c_str(), m_Desc.m_Name.c_str());

    if (!klass)
    {
        ztclog::debug("cannot from class %s %s ", m_Desc.m_Namespace.c_str(), m_Desc.m_Name.c_str());
        return false;
    };

    this->m_IsEnum = mono_class_is_enum(klass);

    void *iter = nullptr;
    MonoMethod *method = nullptr;

    while ((method = mono_class_get_methods(klass, &iter)))
    {
        const char *method_name = mono_method_get_name(method);

        MonoMethodSignature *signature = mono_method_signature(method);
        if (signature)
        {
            int param_count = mono_signature_get_param_count(signature);

            mono::Method::Desc desc;
            desc.m_Name = method_name;
            desc.m_NumParam = param_count;

            auto inst = std::make_shared<mono::Method>(desc, method);
            m_Methods[desc] = inst;
        }
    }

    {
        MonoClassField *field;
        void *iter2 = NULL;
        ztclog::info("clazz: %s", m_Desc.m_Name.c_str());

        while ((field = mono_class_get_fields(klass, &iter2)))
        {
            const char *field_name = mono_field_get_name(field);
            MonoType *fieldType = mono_field_get_type(field);
            const char *typeName = mono_type_get_name(fieldType);

            // new Inst
            auto field = std::make_shared<mono::Field>();
            field->m_Name = field_name;
            field->m_Type = typeName;
            field->monoType = fieldType;

            if (m_IsEnum)
            {
                m_EnumValues.push_back(field);
            }
            else
            {
                m_Fields.push_back(field);
            }

            ztclog::info("%s %s", typeName, field_name);
        }
    }

    return true;
};

bool Clazz::LoadMethod(const Method::Desc &desc)
{
    auto inst = std::make_shared<Method>(desc);
    if (inst->m_Available)
    {
        m_Methods[desc] = inst;
    }
    return inst->m_Available;
}


std::shared_ptr<Method> Clazz::GetMethod(const std::string &name, int numParam)
{

    Method::Desc desc;
    desc.m_Name = name;
    desc.m_NumParam = numParam;
    desc.clazz = klass;

    return m_Methods[desc];
};